﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TST.SharePointObjects.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace TST.SharePointObjects.WebControls
{
    public class SiteInfo : UserControl
    {
        protected Label labelSiteTitle;
        protected Label labelIndexed;
        private SharePointObjectsDatabase _database;
        protected LinkButton runIndex;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            runIndex.Click += new EventHandler(runIndex_Click);
            GetSiteInfo();
        }

        private void runIndex_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                Indexer.FindAndStartJob();
            }
            );
            SPUtility.Redirect(Page.Request.Url.ToString(), SPRedirectFlags.UseSource, System.Web.HttpContext.Current);
        }

        public SharePointObjectsDatabase Database
        {
            get { return _database; }
            set { _database = value; }
        }

        private void GetSiteInfo()
        {
            runIndex.Visible = true;
            labelSiteTitle.Text = SPContext.Current.Web.Title;
            if (Database == null)
            {
                labelIndexed.Text = "No SharePoint Objects Database found.";
                labelIndexed.ForeColor = System.Drawing.Color.Red;
                labelIndexed.Font.Bold = true;
                runIndex.Visible = false;
                return;
            }
            if (!Indexer.JobIsInstalled())
            {
                labelIndexed.Text = "SharePoint Objects Timerjob not installed.";
                labelIndexed.ForeColor = System.Drawing.Color.Red;
                labelIndexed.Font.Bold = true;
                runIndex.Visible = false;
                return;
            }
            SiteInfoStore info = new SiteInfoStore(SPContext.Current.Site.ID, SPContext.Current.Web.ID, SPContext.Current.Site.WebApplication.Id, SPContext.Current.Site.WebApplication.Farm.Id, Database);
            if (info.GetInfo())
            {
                labelIndexed.Text = string.Format(SPContext.Current.Web.Locale, "{0}", info.Indexed);
            }
            else
            {
                labelIndexed.Text = "This site has not been indexed.";
            }
        }

    }
}
